package com.bonorsoft.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;


public class WxTokenAPI {

	private final static String appid = "wxc75bb1b17e911a20";
	private final static String appserct = "299ebe9497552b32b8360650752cc190";

	public static JSONObject getPeopleInfo(String code){
		//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
		String URL="https://api.weixin.qq.com/sns/jscode2session?"
				+ "appid="+ appid +""
				+ "&secret="+ appserct +""
				+ "&js_code="+ code  +""
				+ "&grant_type=authorization_code";
		JSONObject jsonObject = httpRequest(URL, "GET", null);
		System.out.println(jsonObject);
		try {
			if(jsonObject.getString("errcode")!=null){
				return null;
			}else {
				return jsonObject;
			}
		}catch (Exception e) {
			return null;
		}
	}


	public static void payFoods(){

		String requestUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		requestUrl = requestUrl.replace("appid", appid);
		requestUrl = requestUrl.replace("SECRET", appserct);
		JSONObject jsonObject = httpRequest(requestUrl, "POST", null);

	}

	/**
	 * 获取微信公众号的access_token
	 * @return 
	 */
	public static  String getAccessToken() {
		
		String URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid
		+"&secret="+appserct;

		JSONObject jsonObject = httpRequest(URL, "GET", null);  
		try {
			if(jsonObject.getString("errcode")!=null){
				
			}
		}catch (Exception e) {
		}
		 System.out.println(jsonObject);
		 String access_token=jsonObject.getString("access_token");
		return access_token;
		
	}
	
	public static void redirectByAuthType(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		
		String code = request.getParameter("code");
		
		if (code == null || code.length() == 0) {
			String weixinOauthURL = "https://open.weixin.qq.com/connect/oauth2/authorize?"
					+ "appid=wx1dfd64bbdde79997"
					+ "&redirect_uri=http://www.williamsunshine.club/wechatController?wechat"
					+ "&response_type=code"
					+ "&scope=snsapi_base"
					+ "&state=STATE#wechat_redirect";
			response.sendRedirect(weixinOauthURL);
		}else {
			String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
            requestUrl = requestUrl.replace("APPID", appid);
            requestUrl = requestUrl.replace("SECRET", appserct);
            requestUrl = requestUrl.replace("CODE", code);
			com.alibaba.fastjson.JSONObject json2 = httpRequest(requestUrl, "POST", null);
			System.out.println(json2);
			 String openid = (String) json2.get("openid");
			 System.out.println("----------------get--openid-----------------" + openid);
		}
		
		
	}
	
	
		public static  String getUserInfo(String token, String openid2) {
			String accessToken = getAccessToken();
			String URL="https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid="+ appid +""
				+ "&secret="+ appserct +""
				+ "&code="+ accessToken  +""
				+ "&grant_type=authorization_code";

		JSONObject jsonObject = httpRequest(URL, "GET", null);  
		try {
			if(jsonObject.getString("errcode")!=null){
				
			}
		}catch (Exception e) {
		}
		 System.out.println(jsonObject);
		 String openid=jsonObject.getString("openid");
		return openid;
		
	}

	
	public static  JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            //HttpURLConnection设置网络超时
            httpUrlConn.setConnectTimeout(4500);
            httpUrlConn.setReadTimeout(4500);

//			httpUrlConn.setRequestProperty("content-type", "text/html");
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
            // jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
        } catch (Exception e) {
        } finally {
            try {
                httpUrlConn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
	}
	
}
